package vn.vfriends.mcms.site.bean;

import java.io.File;
import java.io.Serializable;
import javax.enterprise.context.RequestScoped;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;
import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import vn.vfriends.mcms.site.model.Site;
import vn.vfriends.mcms.site.service.SiteService;

/**
 *
 * @author tuan@vfriends.vn
 */
@Named
@RequestScoped
public class DisplayBean implements Serializable {

    private static final Logger logger = LoggerFactory.getLogger(DisplayBean.class);
    
    private String siteName;
    
    private String path;
    
    @Inject private SiteService siteService;

    public String getSiteName() {
        return siteName;
    }

    public void setSiteName(String siteName) {
        this.siteName = siteName;
    }

    public String getPath() {
        return path;
    }

    public void setPath(String path) {
        this.path = path;
    }
    
    public void preRenderAction() {
        FacesContext context = FacesContext.getCurrentInstance();
        try {
            ServletContext servletContext = (ServletContext) context.getExternalContext().getContext();
            String localPath = servletContext.getInitParameter("LOCAL_PATH");
            Site site = this.siteService.findSiteByName(siteName);
            if(StringUtils.isEmpty(path) || path.trim().equals("/")) {
                path = "index.html";
            }
            File file = new File(localPath + site.getName() + File.separator + path);
            byte[] contents;
            if(!file.exists()) {
                contents = "The page is not found".getBytes("UTF-8");
            } else {
                contents = FileUtils.readFileToByteArray(file);
            }
            HttpServletResponse response = (HttpServletResponse)context.getExternalContext().getResponse();
            ServletOutputStream out = response.getOutputStream();
            out.write(contents);
            out.close();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        context.responseComplete();
    }
}
